﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Indigo.Quibbler.Data;
using System.Configuration;
using System.IO;
using System.Xml;
using System.Windows.Media.Effects;
using System.Windows.Threading;

namespace Indigo.Quibbler.Controls
{
    public enum SectionControlMode
    {
        Overview, Details
    }
    /// <summary>
    /// Interaction logic for SectionControl.xaml
    /// </summary>
    public partial class SectionControl : UserControl
    {
        private DispatcherTimer _effectTimer = new DispatcherTimer();

        public SectionControl()
        {
            this.InitializeComponent();
            _effectTimer.Interval = TimeSpan.FromSeconds(10);
            _effectTimer.Tick += new EventHandler(_EffectTimer_Tick);
        }



        #region Dependency Property
        public string Category
        {
            get { return (string)GetValue(CategoryProperty); }
            set { SetValue(CategoryProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Title.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CategoryProperty =
            DependencyProperty.Register("Category", typeof(string), typeof(SectionControl), new PropertyMetadata(OnCategoryChanged));

        public List<NewsArticle> ItemSource
        {
            get { return (List<NewsArticle>)GetValue(ItemSourceProperty); }
            set { SetValue(ItemSourceProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Title.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ItemSourceProperty =
            DependencyProperty.Register("ItemSource", typeof(List<NewsArticle>), typeof(SectionControl), new PropertyMetadata(ItemSourceChanged));

        public SectionControlMode Mode
        {
            get { return (SectionControlMode)GetValue(ModeProperty); }
            set { SetValue(ModeProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Mode.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ModeProperty =
                DependencyProperty.Register("Mode", typeof(SectionControlMode), typeof(SectionControl), new PropertyMetadata(SectionControlModeChanged));




        public bool IsUpdated
        {
            get { return (bool)GetValue(IsUpdatedProperty); }
            set { SetValue(IsUpdatedProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsUpdated.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsUpdatedProperty =
            DependencyProperty.Register("IsUpdated", typeof(bool), typeof(SectionControl), new PropertyMetadata(IsUpdatedChanged));


        #endregion

        #region Static Handlers
        private static void ItemSourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            (obj as SectionControl).OnItemsSourceChanged(e);
        }

        private static void SectionControlModeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            (obj as SectionControl).OnSectionControlModeChanged(e);
        }

        private static void OnCategoryChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            (obj as SectionControl).OnSectionControlCategoryChanged(e);
        }

        private static void IsUpdatedChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            (obj as SectionControl).OnIsUpdatedChanged(e);
        }
        #endregion

        void _EffectTimer_Tick(object sender, EventArgs e)
        {
            gridUpdated.Visibility = Visibility.Collapsed;
            _effectTimer.Stop();
            this.SetValue(SectionControl.IsUpdatedProperty, false);
        }

        private void OnSectionControlModeChanged(DependencyPropertyChangedEventArgs e)
        {
            if ((SectionControlMode)e.NewValue == SectionControlMode.Details)
            {
                //(this.Resources["sbShowDetails"] as System.Windows.Media.Animation.Storyboard).Begin();
                gridDetails.Visibility = Visibility.Visible;
                gridDetails.Opacity = 100;
                gridOverview.Visibility = Visibility.Collapsed;
            }
            else if ((SectionControlMode)e.NewValue == SectionControlMode.Overview)
            {
                (this.Resources["sbShowOverview"] as System.Windows.Media.Animation.Storyboard).Begin();
            }
        }

        private void OnSectionControlCategoryChanged(DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue.ToString().ToLower().Equals("photos"))
            {
                gridImage.Visibility = Visibility.Visible;
                //gridUpdated.Margin = new Thickness(0, 41,0, 40);
                BitmapDecoder decoder = BitmapDecoder.Create(new Uri("pack://application:,,/Quibbler - Universal News Reader;component/Images/SectionPhotos.png", UriKind.RelativeOrAbsolute), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                ImageSource iconSource = decoder.Frames[0];
                img.Source = iconSource;
            }
            else if (e.NewValue.ToString().ToLower().Equals("videos"))
            {
                gridImage.Visibility = Visibility.Visible;
                BitmapDecoder decoder = BitmapDecoder.Create(new Uri("pack://application:,,/Quibbler - Universal News Reader;component/Images/SectionVideos.png", UriKind.RelativeOrAbsolute), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                ImageSource iconSource = decoder.Frames[0];
                img.Source = iconSource;
            }
            else
                gridCategory.Visibility = Visibility.Visible;
            //this.SetValue(SectionControl.IsUpdatedProperty, true);
        }

        private void OnIsUpdatedChanged(DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                gridUpdated.Visibility = Visibility.Visible;
                _effectTimer.Start();
            }
        }

        private void OnItemsSourceChanged(DependencyPropertyChangedEventArgs e)
        {
            if ((e.NewValue as List<NewsArticle>).Count == 0)
                lblContentUnavailable.Visibility = Visibility.Visible;
        }
    }

    public class GradientShades
    {
        public string DarkShade { get; set; }
        public string LightShade { get; set; }
    }

    public class SectionTitleConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return (value != null) ? value.ToString() : value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }

        #endregion
    }

    public class GradientDarkShadeConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                return (CategoryColorCodes.GetGradient(value.ToString().ToLower().Trim())).DarkShade;
            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }

        #endregion
    }

    public class GradientLightShadeConverter : IValueConverter
    {
        public static int number = 0;
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                return (CategoryColorCodes.GetGradient(value.ToString().ToLower().Trim())).LightShade;
            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }

        #endregion
    }

    public class SectionControlViewModeConverter : IValueConverter
    {
        public static int number = 0;
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                if (((SectionControlMode)value).ToString() == parameter.ToString())
                    return Visibility.Visible;
                else
                    return Visibility.Hidden;
            }
            return Visibility.Hidden;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }

        #endregion
    }

    public class CategoryColorCodes
    {
        private static Random _rand = new Random();
        private static int _lastSavedColorIndex = -1;

        public static GradientShades GetGradient(string category)
        {
            category = category.Trim().ToLower();
            string _CategoriesFileNameWithPath = "CategoryColors.xml";
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(_CategoriesFileNameWithPath);
            }
            catch (FileNotFoundException ex)
            {
                //if file is not found, create a new xml file
                XmlTextWriter xmlWriter = new XmlTextWriter(_CategoriesFileNameWithPath, System.Text.Encoding.UTF8);
                xmlWriter.Formatting = Formatting.Indented;
                xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
                xmlWriter.WriteDocType("Categories", null, null, "<!ELEMENT Categories ANY><!ELEMENT Category ANY> <!ATTLIST Category Name ID #REQUIRED>");
                xmlWriter.WriteStartElement("Categories");
                xmlWriter.Close();
                xmlDoc.Load(_CategoriesFileNameWithPath);
            }
            catch
            { return _GetColorCode(""); }
            XmlNode xmlNode = xmlDoc.GetElementById(category);
            string color = string.Empty;

            if (xmlNode == null)
            {
                try
                {
                    color = _GetRandomColor();
                    XmlElement newNode = _CreateNewNode(xmlDoc, "Category", color);
                    XmlAttribute xmlAttr = xmlDoc.CreateAttribute("Name");
                    xmlAttr.Value = category;
                    newNode.SetAttributeNode(xmlAttr);
                    xmlDoc.DocumentElement.AppendChild(newNode);
                    xmlDoc.Save(_CategoriesFileNameWithPath);
                }
                catch { ;}
            }
            else
                color = xmlNode.InnerText.ToString().ToLower();

            return _GetColorCode(color);
        }

        private static XmlElement _CreateNewNode(XmlDocument xmlDoc, string nodeName, string nodeInnerValue)
        {
            XmlElement xmlNode = xmlDoc.CreateElement(nodeName);
            if (!String.IsNullOrEmpty(nodeInnerValue))
                xmlNode.InnerText = nodeInnerValue;
            return xmlNode;
        }


        private static GradientShades _GetColorCode(string color)
        {
            switch (color.ToLower().Trim())
            {
                //    case "green": return new GradientShades() { DarkShade = "#FF3BA700", LightShade = "#FFAEF200" };
                //    case "orange": return new GradientShades() { DarkShade = "#FFF36F24", LightShade = "#FFFFCF6A" };
                //    case "magenta": return new GradientShades() { DarkShade = "#FF9A459A", LightShade = "#FFB03F97" };
                //    case "dark blue": return new GradientShades() { DarkShade = "#FF2E439B", LightShade = "#FF615AA7" };
                //    case "yellow": return new GradientShades() { DarkShade = "#FFFFCE02", LightShade = "#FFFFF200" };
                //    case "sky blue": return new GradientShades() { DarkShade = "#FF00AFEF", LightShade = "#FF91D8F9" };
                //    case "gray": return new GradientShades() { DarkShade = "#FF6D6F71", LightShade = "#FFB8BABC" };
                //    case "pink": return new GradientShades() { DarkShade = "#FFEB008A", LightShade = "#FFEE4E9B" };
                //    default: return new GradientShades() { DarkShade = "#FF00AFEF", LightShade = "#FF91D8F9" }; //Sky Blue
                //

                case "home": return new GradientShades() { DarkShade = "#FF5FAAC1", LightShade = "#FFA0CBDB" };
                case "india": return new GradientShades() { DarkShade = "#FFDE9569", LightShade = "#FFEEC2A9" };
                case "world": return new GradientShades() { DarkShade = "#FFD0C15A", LightShade = "#FFE4DA9B" };
                case "city": return new GradientShades() { DarkShade = "#FF2E439B", LightShade = "#FF615AA7" };
                case "entertainment": return new GradientShades() { DarkShade = "#FFDC7576", LightShade = "#FFE9AFAE" };
                case "business": return new GradientShades() { DarkShade = "#FF7FAF65", LightShade = "#FFB3D0A4" };
                case "sports": return new GradientShades() { DarkShade = "#FF56C5BE", LightShade = "#FFA2DEDC" };
                case "life": return new GradientShades() { DarkShade = "#FFC88BE8", LightShade = "#FFDFBCF4" };
                case "movie": return new GradientShades() { DarkShade = "#FFA392E0", LightShade = "#FFCCC3EE" };
                case "recent": return new GradientShades() { DarkShade = "#FFBE8870", LightShade = "#FFDCBCAF" };
                default: return new GradientShades() { DarkShade = "#FF00AFEF", LightShade = "#FF91D8F9" }; //Sky Blue

            }
        }

        private static List<string> _colors = new List<string>() { "home", "india", "world", "city", "entertainment", "business", "sports", "life", "movie", "recent" };

        private static string _GetRandomColor()
        {
            if (_lastSavedColorIndex == -1)
            {
                _lastSavedColorIndex = _rand.Next(0, _colors.Count - 1);
            }
            else
            {
                int curColorIndex = _lastSavedColorIndex;
                while (curColorIndex == _lastSavedColorIndex)
                {
                    curColorIndex = _rand.Next(0, _colors.Count - 1);
                }
                _lastSavedColorIndex = curColorIndex;
            }
            return _colors[_lastSavedColorIndex];
        }
    }
}